<?php

namespace App\Models\Admin;

use Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
/**
 * sun add passport [HasApiTokens]
 */
use Laravel\Passport\HasApiTokens;

class AdminUser extends Authenticatable
{
    //软删除
    use SoftDeletes;
    /**
     * sun add passport HasApiTokens
     */
    use HasApiTokens, Notifiable;
    protected $table = 'admin_users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'real_name', 'phone', 'photo', 'ip', 'area_id', 'wxno', 'level', 'business_hall_id', 'logined_at'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public $my_permissions = [];
    /**
     * [boot description]
     * @return [type] [description]
     */
    // public function __construct() {
    //     $UserGroupRolePermission = $this->getUserGroupRolePermission();
    //     $UserRolePermission = $this->getUserRolePermission();
    //     $UserPermission = $this->getUserPermission();

    //     $allPermission = array_merge($UserGroupRolePermission,$UserRolePermission,$UserPermission);
    //     $Permission = array();
    //     foreach ($allPermission as $key => $value) {
    //         $Permission[]=$value['name'];
    //     }
    //     $this->my_permissions = $Permission;
    // }

    /**
     * 将密码加密
     * @param [type] $value [description]
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    // 用户-角色
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'admin_role_user', 'user_id', 'role_id');
    }

    // 用户-角色组
    public function groups()
    {
        return $this->belongsToMany(Group::class, 'admin_group_user', 'user_id', 'group_id');
    }

    // 用户-权限
    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'admin_permission_user', 'user_id', 'permission_id');
    }

    /**
     * 关联关系
     * [area 通过地区的属性,获得地区级别以及地区的详细信息]
     * @return [type] [description]
     */
    public function area()
    {
        return $this->hasOne(\App\Models\Inventory\Area::class, 'f_id', 'area_id');
    }

    /**
     * 关联关系
     * [business_hall_id 通过营业厅id获得营业厅的信息]
     * @return [type] [description]
     */
    public function businessHall()
    {
        return $this->hasOne(\App\Models\Inventory\BusinessHall::class, 'id', 'business_hall_id');
    }

    // 通知, 现在用的是message
    public function notifications($limit = 20)
    {
        return $this->belongsToMany(\App\Models\Inventory\Message::class, 'user_messages', 'user_id', 'message_id')->whereNull('user_messages.deleted_at')->withPivot(['user_id', 'message_id', 'read_at'])->recent()->with('user')->paginate($limit);
    }

    // 判断用户是否具有某个角色
    public function hasRole($role)
    {
        if (is_string($role)) {
            return $this->roles->contains('name', $role);
        }
        return !!$role->intersect($this->roles)->count();
    }

    // 判断用户是否具有某权限
    public function hasPermission($permission)
    {
        if (is_string($permission)) {
            $permission = Permission::where('name', $permission)->first();
            if (!$permission) {
                return false;
            }

        }
        return $this->hasRole($permission->roles);
    }

    // 判断用户是否具有某字段的权限
    public function hasPermissionDictionary($dictionary)
    {
        if (is_string($dictionary)) {
            $dictionary = Dictionary::where('name', $dictionary)->first();
            if (!$dictionary) {
                return false;
            }
        }
        return $this->hasRole($dictionary->roles);
    }

    // 判断用户权限
    public function hasUserPermission($UserPermission)
    {
        $UserPermission = Permission::join('admin_permission_user', 'admin_permission_user.permission_id', '=', 'admin_permissions.id')->select(['admin_permission_user.*', 'admin_permissions.*'])->where('admin_permission_user.permission_id', '=', $UserPermission['permission_id'])->where('admin_permission_user.user_id', '=', $UserPermission['user_id'])->get()->toArray();
        if ($UserPermission) {
            return true;
        } else {
            return false;
        }
    }

    // 获取到所有的权限
    public function getUserGroupRole()
    {
        $UserPermission = Permission::all()->toArray();
        return $UserPermission;
    }

    // 判断用户是否具有某权限
    public function hasUserGroupRole($UserPermission)
    {
        $user_id        = Auth::guard(config('inventory.base.guard'))->user()->id;
        $UserPermission = AdminUser::leftjoin('admin_group_user', 'admin_group_user.user_id', '=', 'admin_users.id')
            ->leftjoin('admin_group_role', 'admin_group_role.group_id', '=', 'admin_group_user.group_id')
            ->leftjoin('admin_permission_role', 'admin_permission_role.role_id', '=', 'admin_group_role.role_id')
            ->leftjoin('admin_permissions', 'admin_permissions.id', '=', 'admin_permission_role.permission_id')
            ->select(['admin_users.id as user_id', 'admin_permissions.*', 'admin_permissions.id'])
            ->where('admin_users.id', '=', $user_id)->Where('admin_permissions.id', '=', $UserPermission['id'])->get()->toArray();

        if ($UserPermission) {
            return true;
        } else {
            return false;
        }
    }

    // 获取到所有的权限
    public function getAllPermission()
    {
        $UserPermission = Permission::all()->toArray();
        return $UserPermission;
    }

    // 获取用户组角色权限关联的信息
    public function getUserGroupRolePermission()
    {
        $user_id                 = Auth::guard(config('inventory.base.guard'))->user()->id;
        $UserGroupRolePermission = AdminUser::leftjoin('admin_group_user', 'admin_group_user.user_id', '=', 'admin_users.id')
            ->leftjoin('admin_group_role', 'admin_group_role.group_id', '=', 'admin_group_user.group_id')
            ->leftjoin('admin_permission_role', 'admin_permission_role.role_id', '=', 'admin_group_role.role_id')
            ->leftjoin('admin_permissions', 'admin_permissions.id', '=', 'admin_permission_role.permission_id')
            ->select(['admin_permissions.*'])
            ->where('admin_users.id', '=', "$user_id")->get()->toArray();
        return $UserGroupRolePermission;
    }

    // 获取用户角色权限关联的信息
    public function getUserRolePermission()
    {
        $user_id            = Auth::guard(config('inventory.base.guard'))->user()->id;
        $UserRolePermission = AdminUser::leftjoin('admin_role_user', 'admin_role_user.user_id', '=', 'admin_users.id')
            ->leftjoin('admin_permission_role', 'admin_permission_role.role_id', '=', 'admin_role_user.role_id')
            ->leftjoin('admin_permissions', 'admin_permissions.id', '=', 'admin_permission_role.permission_id')
            ->select(['admin_permissions.*'])
            ->where('admin_users.id', '=', "$user_id")->get()->toArray();
        return $UserRolePermission;
    }

    // 获取用户权限信息
    public function getUserPermission()
    {
        $user_id = Auth::guard(config('inventory.base.guard'))->user()->id;

        $UserPermission = Permission::leftjoin('admin_permission_user', 'admin_permission_user.permission_id', '=', 'admin_permissions.id')->select(['admin_permissions.*'])->Where('admin_permission_user.user_id', '=', "$user_id")->get()->toArray();

        return $UserPermission;
    }

    /**
     * [getUserAllPermission 获得用户的所有权限]
     * @return [type] [description]
     */
    public function getUserAllPermission()
    {
        if (count($this->my_permissions) == 0) {
            $UserGroupRolePermission = $this->getUserGroupRolePermission();
            $UserRolePermission      = $this->getUserRolePermission();
            $UserPermission          = $this->getUserPermission();

            $allPermission = array_merge($UserGroupRolePermission, $UserRolePermission, $UserPermission);
            $permissions   = array();
            foreach ($allPermission as $key => $value) {
                $permissions[] = $value['name'];
            }
            $this->my_permissions = $permissions;
        }
        return $this->my_permissions;
    }

    /**
     * scope
     * [scopeVisualRange 用户可见的区域Region]
     * @return [type] [description]
     */
    public function scopeVisualRegion($query)
    {
        // 根据账号信息的区域属性和营业厅属性【营业厅属性不为空则只能查询到该营业厅的数据，否则可以查看该改区域下的用户数据】限制获取范围过滤
        $area_id          = Auth::guard(config('inventory.base.guard'))->user()->area_id;
        $business_hall_id = Auth::guard(config('inventory.base.guard'))->user()->business_hall_id;
        if (!empty($business_hall_id)) {
            $query->where('business_hall_id', '=', $business_hall_id);
        } else {
            if (!empty($area_id)) {
                $query->where('area_id', '=', $area_id)->orWhere('area_id', 'like', $area_id . '.%');
            } else {
                $query->where('area_id', '=', -1);
            }
        }
    }

    /**
     * [findForPassport passport通过手机号/账号验证]
     * @param  [type] $username [description]
     * @return [type]           [description]
     */
    public function findForPassport($username)
    {
        // if (!$this->where('phone', $username)->first()) {
        //     return $this->where('name', $username)->first();
        // }
        // return true;

        return $this->where('phone', $username)->first();

        // return $this->where('phone', $username)->first() || $this->where('name', $username)->first();
    }

    /**
     * 获得该账户所属SP信息。
     */
    public function sp()
    {
        return $this->belongsTo('App\Models\Common\EntityData\Channel\Sp','sp_id');
    }
}
